//
//  EntertainmentTableViewController.m
//  WildDonkey
//
//  Created by 佟小波 on 15/3/27.
//  Copyright (c) 2015年 lanou. All rights reserved.
//

#import "EntertainmentTableViewController.h"
#import "MovieTableViewCell.h"
#import "MovieData.h"
#import "UIImageView+WebCache.h"
#import "VideosdetailViewController.h"
#import "MJRefresh.h"

@interface EntertainmentTableViewController ()
@property (nonatomic,retain)UIActivityIndicatorView *activity;
//@property (nonatomic,retain)NSMutableArray *dataArr;
@property (assign, nonatomic) NSInteger currentPage;
@property (nonatomic,retain)NSMutableData *receivedData;//拼接新数据
@property (nonatomic,retain)NSMutableArray *MoviesArray;
//@property (nonatomic,assign)NSInteger page;
@end
static int _page = 1;
@implementation EntertainmentTableViewController
- (void)dealloc
{
    [_cell release];
    [_activity release];
    //[_dataArr release];
    [_receivedData release];
    [_MoviesArray release];
    
    [super dealloc];
}


//接到回应
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    if (_MoviesArray.count != 0) {
        
    }else{
        self.MoviesArray = [NSMutableArray array];
    }
    self.receivedData = [NSMutableData data];
    
}
//服务器多次返回数据的方法
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    //    NSLog(@"---%d",[data length]);
    [self.receivedData appendData:data];
    //    NSLog(@"--------%.2f",1.0*[self.receivedData length]/self.totalLength);
    
}
//下载完毕结束的时候
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:self.receivedData options:NSJSONReadingMutableContainers error:nil];
    NSDictionary *array = [dic objectForKey:@"list"];
    //self.MoviesArray = [NSMutableArray arrayWithCapacity:[array count]];
    
    for (NSDictionary *dic in array) {
        MovieData *bjdata = [[MovieData alloc]init];
        [bjdata setValuesForKeysWithDictionary:dic];
        [self.MoviesArray addObject:bjdata];
        [bjdata release];
        
    }
    
    [self.tableView reloadData];//相当于刷新
    //[_activity stopAnimating];
}
//请求超时 有错误等等执行的方法
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
    NSLog(@"%@",error);
}

- (void)setupRefreshView
{
    //设置头部刷新
    [self.tableView addLegendHeaderWithRefreshingTarget:self refreshingAction:@selector(addLegendHeaderWithRefreshing) dateKey:nil];
    
    [self.tableView.header beginRefreshing];//进入程序就执行刷新
    //设置上拉加载数据
    [self.tableView addLegendFooterWithRefreshingTarget:self refreshingAction:@selector(addLegendFooterWithRefreshing)];
}
- (void)addLegendHeaderWithRefreshing
{
    int x = 205;
    NSString *str = [NSString stringWithFormat:@"http://api.budejie.com/api/api_open.php?a=newlist&appname=baisishequ&asid=93E4AE6F-8ACB-4B08-A321-4633543F6F9E&c=video&client=iphone&device=iPhone%d&from=ios&jbk=0&mac=&market=&openudid=e0382b752bef59df89921d75a689d93f1c4cc5e7&page=%d&per=20&type=41&udid=&ver=3.2",x,_page];
    NSURL *url = [NSURL URLWithString:str];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    [NSURLConnection connectionWithRequest:request delegate:self];
    
    [self.tableView reloadData];
    [self.tableView.header endRefreshing];
}

- (void)addLegendFooterWithRefreshing
{
    NSLog(@"%d",_page);
    _page = _page + 1;
    int x= 205;
    NSString *str = [NSString stringWithFormat:@"http://api.budejie.com/api/api_open.php?a=newlist&appname=baisishequ&asid=93E4AE6F-8ACB-4B08-A321-4633543F6F9E&c=video&client=iphone&device=iPhone%d&from=ios&jbk=0&mac=&market=&openudid=e0382b752bef59df89921d75a689d93f1c4cc5e7&page=%d&per=20&type=41&udid=&ver=3.2",x,_page];
    
    NSURL *url = [NSURL URLWithString:str];
    
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    [NSURLConnection connectionWithRequest:request delegate:self];
    
    [self.tableView reloadData];
    
    [self.tableView.footer endRefreshing];
    
}
- (void)viewDidLoad {
    [super viewDidLoad];
    [self setupRefreshView];//调用自动刷新
    
    //[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(playAudio) name:@"playing" object:nil];
    
    //
    //    NSURL *url = [NSURL URLWithString:@"http://api.budejie.com/api/api_open.php?a=list&appname=baisishequ&asid=93E4AE6F-8ACB-4B08-A321-4633543F6F9E&c=video&client=iphone&device=iPhone%205&from=ios&jbk=0&mac=&market=&openudid=e0382b752bef59df89921d75a689d93f1c4cc5e7&page=0&per=20&type=41&udid=&ver=3.2"];
    //    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    //    [NSURLConnection connectionWithRequest:request delegate:self];
    
    
    UIImage *image1 = [[[UIImage alloc]init]autorelease];
    image1 = [UIImage imageNamed:@"BarButton"];
    
    UIButton *BarButton = [UIButton buttonWithType:UIButtonTypeCustom];
    BarButton.frame = CGRectMake(0, 0, 20, 20);
    [BarButton setImage:image1 forState:UIControlStateNormal];
    [BarButton addTarget:self action:@selector(aa) forControlEvents:UIControlEventTouchUpInside];
    
    UIBarButtonItem *button = [[[UIBarButtonItem alloc]initWithCustomView:BarButton]autorelease];
    self.navigationItem.leftBarButtonItem=button;
    
    
}

-(void)aa
{
    [self.navigationController popViewControllerAnimated:YES];
}

//- (void)setupRefreshView
//{
//    UIRefreshControl *refreshControl =[[[UIRefreshControl alloc]init]autorelease];
//    [refreshControl addTarget:self action:@selector(refreshstateChange:) forControlEvents:UIControlEventValueChanged];
//    [self.tableView addSubview:refreshControl];
//}
//- (void)refreshstateChange:(UIRefreshControl *)refreshcontrol
//{
//    //NSLog(@"正在刷新");
//    NSURL *url = [NSURL URLWithString:@"http://api.budejie.com/api/api_open.php?a=list&appname=baisishequ&asid=93E4AE6F-8ACB-4B08-A321-4633543F6F9E&c=video&client=iphone&device=iPhone%205&from=ios&jbk=0&mac=&market=&openudid=e0382b752bef59df89921d75a689d93f1c4cc5e7&page=0&per=20&type=41&udid=&ver=3.2"];
//    NSURLRequest *request = [NSURLRequest requestWithURL:url];
//    [NSURLConnection connectionWithRequest:request delegate:self];
//    [refreshcontrol endRefreshing];
//
//
//}
//#pragma mark 上拉刷新
//- (void)headerRereshing
//{
//    [self.tableView headerEndRefreshing];
//}
//#pragma mark 下拉加载
//- (void)footerRereshing
//{
//    [self loadDataAndShow];
//    [self.tableView footerEndRefreshing];
//}
//- (void)loadDataAndShow
//{
//
//}

//- (void)addHeader
//{
//    [self.myCollecView addHeaderWithCallback:^{
//        [self.myCollecView headerBeginRefreshing];
//    }];
//}
//- (void)addFooter
//{
//    [self.myCollecView addFooterWithCallback:^{
//        [self.myCollecView footerBeginRefreshing];
//    }];
//
//}

//-(void)setupRefresh
//{
//    UIRefreshControl *control=[[UIRefreshControl alloc]init];
//    control.tintColor=[UIColor redColor];
//    control.attributedTitle=[[NSAttributedString alloc]initWithString:@"刷新中"];
//    [control addTarget:self action:@selector(refreshStateChang:) forControlEvents:UIControlEventValueChanged];
//    [self.tableView addSubview:control];
//    [control beginRefreshing];
//    [self  refreshStateChang:control];
//
//
//}

//-(void)refreshStateChang:(UIRefreshControl *)control
//{
//
//
//
//}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    MovieData *moviedata = self.MoviesArray[indexPath.row];
    //return [MovieTableViewCell heightForString:moviedata.text] + 50 + moviedata.height;
    //    if (DataHeight.width >= 320) {
    //        //NSLog(@"宽度大的试图为：%d",_cell.height);
    //        return  _cell.height + [BJTableViewCell heightForString:DataHeight.text] + 80;
    //    }
    //    return DataHeight.height + [BJTableViewCell heightForString:DataHeight.text] + 80;
    CGFloat aa = [UIScreen mainScreen].bounds.size.width; //_cell.bounds.size.width;
    if (moviedata.height >= aa) {
        return _cell.height + [MovieTableViewCell heightForString:moviedata.text] + 80;
    }
    return moviedata.height + [MovieTableViewCell heightForString:moviedata.text] + 80;
    
}



- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
#warning Incomplete method implementation.
    // Return the number of rows in the section.
    return [self.MoviesArray count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *reusable = @"reus";
    
    _cell = [tableView dequeueReusableCellWithIdentifier:reusable];
    if (nil == _cell) {
        _cell = [[MovieTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:reusable];
        
    }
    
    // Configure the cell...
    _cell.moviedata = self.MoviesArray[indexPath.row];
    //上面一行代码可以分布为：
    //    MovieData *moviedata = [[MovieData alloc]init];
    //    moviedata = self.MoviesArray[indexPath.row];
    //_cell
    
    //_cell.MovieURl = self.MoviesArray[indexPath.row];
    
    
    
    return _cell;
}



//点击cell 触发事件
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    VideosdetailViewController *movieVC = [[[VideosdetailViewController alloc]init]autorelease];
    movieVC.hidesBottomBarWhenPushed=YES;  //push 进去是隐藏 tabbaritem
    [self.navigationController pushViewController:movieVC animated:YES];
    //    [self.view.superview addSubview:movieVC.view];
    
    //    NSString * str = [[NSString alloc]initWithString:_cell.MovieURl];
    
    //[self.navigationController popViewControllerAnimated:YES];
    movieVC.data=self.MoviesArray[indexPath.row];
    //    NSDictionary *dict = [[NSDictionary alloc]initWithObjectsAndKeys:self.cell.MovieURl,@"urlOnt", nil];
    //    NSLog(@"字典解析出来的是：%@",[dict valueForKey:@"urlOnt"]);
    //    NSLog(@"本地字典解析出来的是：%@",self.cell.MovieURl);
    //    NSNotification *notification = [NSNotification notificationWithName:@"tongzhi" object:nil userInfo:dict];
    //    [[NSNotificationCenter defaultCenter]postNotification:notification];
    
    //[dict release];
}
/*
 // Override to support conditional editing of the table view.
 - (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
 // Return NO if you do not want the specified item to be editable.
 return YES;
 }
 */

/*
 // Override to support editing the table view.
 - (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
 if (editingStyle == UITableViewCellEditingStyleDelete) {
 // Delete the row from the data source
 [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
 } else if (editingStyle == UITableViewCellEditingStyleInsert) {
 // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
 }
 }
 */

/*
 // Override to support rearranging the table view.
 - (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
 }
 */

/*
 // Override to support conditional rearranging of the table view.
 - (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
 // Return NO if you do not want the item to be re-orderable.
 return YES;
 }
 */

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
